#include "network.h"

Network::Network(QObject *parent) : QObject(parent)
{
    //初始化对象
    socket = new QTcpSocket;
    timer = new QTimer;

    //信号与槽连接
    connect(socket,SIGNAL(connected()),this,SLOT(clientConnectedFunc()));
    connect(socket,SIGNAL(disconnected()),this,SLOT(clientDisConnectedFunc()));

    connect(socket,SIGNAL(readyRead()),this,SLOT(readServerMsg()));
    connect(timer,SIGNAL(timeout()),this,SLOT(startTimerOutFunc()));

}

Network::~Network()
{

}

//客户端连接服务器
bool Network::clientConnectToServer(QString serverIpAddress, int serverPort)
{
    //调用 QTcpSocket::connectToHost() 时，Qt 内部会创建一个客户端套接字，
    //向服务端的监听套接字发起连接请求。连接成功后，该套接字成为客户端与服务端通信的专用通道。
    socket->connectToHost(serverIpAddress,serverPort);

    //判断是否在规定时间内连接成功
    if(socket->waitForConnected())
    {
        iCountTestMsg=0;


        return true;
    }
    else
    {
        return false;
    }
}

//客户端向服务器发送消息
void Network::clientSendMsgToServer(QString strData)
{
    //将字符串转换为QByteArray,并发送给另一端
    socket->write((strData + "\n").toUtf8());
}

//服务器向客户端发送信息
void Network::serverSendMsgToClient(QString strData)
{
    //将字符串转换为QByteArray,并发送给另一端
    socket->write(strData.toUtf8());
}



//客户端与服务器之间：连接的操作消息回馈
void Network::clientConnectedFunc()
{

}

//客户端与服务器之间：断开的操作消息回馈
void Network::clientDisConnectedFunc()
{
    timer->stop();
}

//断开与服务器(远程主机)的连接
void Network::disconnectFromHost()
{
    //断开与另一端的连接
    socket->disconnectFromHost();
}

//读取服务器发来的消息
QByteArray Network::readServerMsg()
{
    QByteArray data = socket->readAll();
    return data;
}

//启动定时器自动向服务器发送消息
void Network::startTimerOutFunc()
{
    timer->start(400);
    QString strTemp = QString("\n[Prompt:Client automatic testing(%1)]").arg(iCountTestMsg++);
    clientSendMsgToServer(strTemp);
}

//设置停止定时器自动发送消息
void Network::stopTimerOutFunc()
{
    timer->stop();
}
